import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import storage from '../utils/auth'
import userApi from '../api/user'

export default new Vuex.Store({
  state: {
    token: storage.getToken() ? storage.getToken() : '',
    userInfo: storage.getUserInfo() ? storage.getUserInfo() : '',
  },
  mutations: {
    saveToken(state, token) {
      state.token = token
      storage.setToken(token)
    },
    saveUserInfo(state, userInfo) {
      state.userInfo = userInfo
      storage.setUserInfo(userInfo)
    },
    removeState(state){
      state.token = null;
      state.userInfo = null
      storage.removeTokenAndUserInfo();
    }
  },
  actions: {
    doLogin({ commit }, formName) {
      return new Promise((resolve, reject) => {
        userApi.doLogin(formName.username, formName.password).then(response => {
          if(response.data.flag){
            let token = response.data.data.token
            commit('saveToken',token)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserInfo({commit}){
      return new Promise((resolve, reject) => {
        userApi.getUserInfo().then(response => {
          if(response.data.flag){
            let userInfo = response.data.data
            commit('saveUserInfo',userInfo)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getOut({commit}){
      return new Promise((resolve, reject) => {
        userApi.getOut().then(response=>{
          if(response.data.flag){
            commit('removeState')
          }
          resolve(response)
        }).catch(error=>{
          reject(error)
        })
      })
    }
  },
  modules: {

  },
});
